package com.easy.app.controller;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.easy.framework.common.constant.I18NConstants;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.Func;
import com.easy.framework.common.utils.I18NUtils;
import com.easy.framework.security.model.LoginUser;
import com.easy.framework.security.model.Role;
import com.easy.framework.security.utils.SecurityUtils;
import com.easy.module.system.entity.SysConf;
import com.easy.module.system.entity.SysUser;
import com.easy.module.system.entity.SysUserCredential;
import com.easy.module.system.model.CaptchaResetPwdModel;
import com.easy.module.system.query.SysConfQuery;
import com.easy.module.system.service.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequiredArgsConstructor
public class AppController {

    final OAuth2AuthorizationService authorizationService;

    final ISysMenuService sysMenuService;

    final ISysConfService sysConfService;

    final ISysUserService sysUserService;

    final IEmailCaptchaService emailCaptchaService;


    @GetMapping("/auth/check_token")
    public R checkToken(@RequestHeader("Authorization") String authHeader) {
        String tokenValue = authHeader.replace("Bearer ", "");
        OAuth2Authorization authorization = authorizationService.findByToken(tokenValue, OAuth2TokenType.ACCESS_TOKEN);
        if (authorization == null) {
            return R.fail(HttpStatus.UNAUTHORIZED.value(), I18NUtils.message(I18NConstants.AUTHENTICATION_TOKEN_INVALID));
        }
        return R.success(I18NUtils.message(I18NConstants.AUTHENTICATION_TOKEN_VALID));
    }

    /**
     * 退出登录
     * @param authHeader
     * @return
     */
    @PostMapping("/auth/logout")
    public R logout(@RequestHeader("Authorization") String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
            if (authorization != null) {
                authorizationService.remove(authorization);
                return R.success();
            }
        }
        return R.fail();
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/auth/getInfo")
    public R getInfo() {
        LoginUser user = SecurityUtils.getUser();
        Map<String, Object> data = new HashMap<>();
        data.put("user", sysUserService.getById(user.getUserId()));
        data.put("roleKeys", Optional.ofNullable(user.getRoles()).orElse(new ArrayList<>()).stream().map(Role::getRoleKey).collect(Collectors.toSet()));
        return R.success(data);
    }

    /**
     * 获取用户权限
     *
     * @return
     */
    @GetMapping("/auth/getPermission")
    public R<Set<String>> getPermission() {
        return R.success(SecurityUtils.getPermissions());
//        LoginUser user = SecurityUtils.getUser();
//        return R.success(sysMenuService.getUserAuthorities(user.getUserId(), Optional.ofNullable(user.getRoles()).orElse(new ArrayList<>()).stream().map(Role::getRoleId).collect(Collectors.toList())));
    }

    /**
     * 获取路由信息
     *
     * @return
     */
    @GetMapping("/auth/getRouters")
    public R getRouters() {
        return R.success(sysMenuService.getRouters(SecurityUtils.getUserId()));
    }

    /**
     * 获取系统配置表
     * @param request
     * @param query
     * @return
     */
    @GetMapping("getConfigs")
    public R<List<SysConf>> getConfigs(HttpServletRequest request, SysConfQuery query) {
        String authHeader = request.getHeader("Authorization");
        if (Func.isNotEmpty(authHeader)) {
            String tokenValue = authHeader.replace("Bearer ", "");
            OAuth2Authorization authorization = authorizationService.findByToken(tokenValue, OAuth2TokenType.ACCESS_TOKEN);
            if (authorization != null) {
                query.setInScope(List.of("0", "1"));
                return R.success(sysConfService.list(query));
            }
        }
        query.setScope("0");
        return R.success(sysConfService.list(query));
    }


    /**
     * 通过邮箱重置密码
     *
     * @param data
     * @return
     */
//    @Log(title = "邮箱验证码重置密码", type = Operation.UPDATE)
    @PutMapping("/reset/password")
    public R emailResetPassword(@Validated @RequestBody CaptchaResetPwdModel data) {
        SysUser sysUser = sysUserService.getByUsername(data.getUsername());
        String businessKey = HexUtil.decodeHexStr(data.getCaptchaKey());
        if (Func.isNotEmpty(sysUser) && businessKey.split(":")[0].equals(sysUser.getEmail())) {
            emailCaptchaService.verifyCode(data.getCaptchaKey(), data.getCaptcha());
            sysUserService.updatePassword(sysUser.getId(), SecurityUtils.encryptPassword(data.getNewPassword()));
            return R.success();
        }
        return R.fail();
    }
}
